package com.wwj.my_ummary;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;

public class RedEnvelope {


    public static void main(String[] args) {
        RedPackage redPackage = new RedPackage();
        redPackage.setRemainMoney(BigDecimal.valueOf(10));
        redPackage.setRemainSize(100);

        System.out.println(getRandomMoney(redPackage));
    }

    public static BigDecimal getRandomMoney(RedPackage redPackage) {
        // remainSize 剩余的红包数量
        // remainMoney 剩余的钱
        int remainSize = redPackage.getRemainSize();
        BigDecimal remainMoney = redPackage.getRemainMoney();
        if (remainSize == 1) {
            remainSize--;
            redPackage.setRemainSize(remainSize);
            redPackage.setRemainMoney(BigDecimal.ZERO);
            return remainMoney;
        }
        SecureRandom r = new SecureRandom();
        BigDecimal min = new BigDecimal(0.01);
        BigDecimal max = remainMoney.divide(new BigDecimal(remainSize * 2), 2, RoundingMode.HALF_UP);
        BigDecimal money = max.multiply(new BigDecimal(r.nextInt()));
        if (money.compareTo(new BigDecimal(0.01)) < 0) {
            money = new BigDecimal(0.01);
        }
        remainSize--;
        remainMoney = remainMoney.subtract(money);
        redPackage.setRemainSize(remainSize);
        redPackage.setRemainMoney(remainMoney);
        return money;
    }
}


